package com.yjd.comm.fs.util;

import java.io.File;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import com.yjd.comm.fs.file.IFileService;
import com.yjd.comm.fs.file.IUpWrap;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.HttpsUtil;
import com.yjd.comm.util.HttpsUtil.UploadFileModel;
import com.yjd.comm.util.SpringContextHolder;
import com.yjd.comm.util.StringUtil;
/**
 * 文件上传和下载工具类
 * 
 * @author ready
 * 
 */
public class FileUtil {
	private static Logger logger = Logger.getLogger(FileUtil.class);

	/**
	 * 获取文件服务
	 * 
	 * @return
	 */
	public static IFileService getFileService() {
		return SpringContextHolder.getBean("fileService");
	}

	/**
	 * 上传文件
	 * 
	 * @param uploadUrl
	 *            上传文件的路径
	 * @param inwrapList
	 *            上传文件的列表信息
	 * @return
	 * @throws Exception
	 */
	public static boolean upload(String uploadUrl, List<IUpWrap> inwrapList)
			throws Exception {
		boolean result = true;
		Map<String, UploadFileModel> requestInps = new LinkedHashMap<String, UploadFileModel>();
		Map<String, Object> requestParas = new LinkedHashMap<String, Object>();
		int i = 0;
		for (IUpWrap upWrap : inwrapList) {
			String fileFiledName = "file" + i++;
			requestInps.put(
					fileFiledName,
					new UploadFileModel(upWrap.getInputStream(), upWrap
							.getFileName()));
			requestParas.put(fileFiledName + "AbsPath",
					upWrap.getSaveAbsFilePath());
		}
		logger.debug(FrameUtil.json(requestParas));
		HttpsUtil.requestPostUploadByIs(uploadUrl, requestInps, requestParas);
		return result;
	}

	/**
	 * 下载文件
	 * 
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	public static InputStream downLoadFile(String filePath) throws Exception {
		return HttpsUtil.requestGetResponse(filePath).getResponseStream();
	}

	/**
	 * 下载一个文件到指定的文件中
	 * 
	 * @param filePath
	 * @param file
	 * @throws Exception
	 */
	public static void downLoadFile(String filePath, File file)
			throws Exception {
		FileUtils.copyInputStreamToFile(downLoadFile(filePath), file);
	}

	/**
	 * 根据文件名称获取文件后缀
	 * 
	 * @param fileName
	 * @return
	 */
	public static String getFileStuffByFileName(String fileName) {
		if (StringUtil.isNotEmpty(fileName) && fileName.indexOf(".") != -1) {
			return fileName.substring(fileName.indexOf("."));
		}
		return "";
	}

}
